<template>
  <div :class="['seg-theme', selectedSideClass]">
    <ElSegmented v-model="innerValue" :options="options" />
  </div>
</template>

<script setup lang="ts">
import { ElSegmented } from "element-plus"
import { computed } from "vue"

type Option = string | number | { label: string; value: string | number }

const props = defineProps<{
  modelValue: string | number
  options: Option[]
}>()

const emit = defineEmits<{
  (e: "update:modelValue", val: string | number): void
}>()

const innerValue = computed({
  get: () => props.modelValue,
  set: (val: string | number) => emit("update:modelValue", val)
})

const optionValues = computed<(string | number)[]>(() =>
  props.options.map((o: any) => (typeof o === "object" ? o.value : o))
)
const selectedIndex = computed(() =>
  optionValues.value.findIndex((v) => v === innerValue.value)
)
const selectedSideClass = computed(() => {
  if (selectedIndex.value === 0) return "selected-left"
  if (selectedIndex.value === optionValues.value.length - 1)
    return "selected-right"
  return ""
})
</script>

<style scoped>
/* Rounded pill segmented control themed to app */
.seg-theme {
  border-radius: 9999px;
  background: #d6e6ff;
  padding: 2px;
  max-width: 100%;
  display: inline-block;
}
.seg-theme :deep(.el-segmented) {
  background: transparent;
}
.seg-theme :deep(.el-segmented__group) {
  gap: 4px;
}
.seg-theme :deep(.el-segmented__item) {
  border-radius: 9999px;
  color: var(--fg);
}
.seg-theme :deep(.el-segmented__item-label) {
  padding: 4px 0px;
  font-size: 14px;
}
.seg-theme :deep(.el-segmented__thumb) {
  border-radius: 9999px;
  background: #1489fe;
  border: 1px solid #1489fe;
  box-shadow: none;
}
.seg-theme :deep(.el-segmented__item-selected) {
  border-radius: 9999px !important;
  color: #ffffff !important;
}
.seg-theme :deep(.el-segmented__item.is-selected .el-segmented__item-label) {
  color: #ffffff !important;
}

/* Adaptive rounded side based on selection */
.seg-theme.selected-left :deep(.el-segmented__thumb) {
  border-radius: 9999px 10px 10px 9999px;
}
.seg-theme.selected-right :deep(.el-segmented__thumb) {
  border-radius: 10px 9999px 9999px 10px;
}
</style>
